package cn.yunhe.realm;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import cn.yunhe.dao.UserDao;
import cn.yunhe.entity.User;

public class MyRealm extends  AuthorizingRealm {
	private UserDao userDao;
    /**
     * 授权
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection princ) {
		System.out.println("===================获取 权限-角色数据 ==========================");
		String currUserName = princ.getPrimaryPrincipal().toString();
		Set<String> roles = userDao.getRolesByUsername(currUserName);
		Set<String> perms = userDao.getPermissionsByUsername(currUserName);
		SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();
		authInfo.setRoles(roles);
		authInfo.setStringPermissions(perms);
		return authInfo;
	}
    /**
     * 身份认证 
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("***************************realm执行登录认证*******************************");
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		//获取令牌token中 封装的 用户名和密码
		String  uname = upToken.getUsername();
		//System.out.println(token.getCredentials());
		//String pwd = upToken.getPassword().toString();
		String pwd = new String((char[])upToken.getCredentials());
		System.out.println(uname+"---------------"+pwd);
		User user = userDao.loginUser(uname);
		System.out.println("user:"+user);
		System.out.println(user.getPassword());
		if(user != null){
			System.out.println(getName());
			SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(uname, user.getPassword(),getName());
			ByteSource salt = ByteSource.Util.bytes(uname+pwd);
			authInfo.setCredentialsSalt(salt);
			return authInfo;
		}
		return null;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	public static void main(String[] args) {
		 String uname = "lisi";
		 String pwd = "123";
		 String salt = uname + pwd; //设置盐 , 用户名+源密码
		 int hashIterations = 1024;//加密1024次  
		 SimpleHash sh=new SimpleHash("MD5", pwd, salt, hashIterations);
		 System.out.println(sh);
	}
}
